package com.yxcz.serviceImpl;

import java.util.ArrayList;
import java.util.HashMap;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.yxcz.dao.DeptDAO;
import com.yxcz.dao.PositionDAO;
import com.yxcz.dao.UserDAO;
import com.yxcz.model.UpdateUserForm;
import com.yxcz.model.UpdateUserInfoForm;
import com.yxcz.model.User;
import com.yxcz.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Resource
	private UserDAO userDAO;
	@Resource
	private PositionDAO positionDAO;
	@Resource
	private DeptDAO deptDAO;

	/**
	 * 更新用户信息
	 */
	@Override
	public void updateUserInfo(UpdateUserInfoForm form) {
		User user = userDAO.find(form.getId());
		user.setBirthday(form.getBirthday());
		user.setPhone(form.getPhone());
		user.setMobilePhone(form.getMobilePhone());
		user.setSex(form.isSex());
		user.setBusiness(form.getBusiness());
		userDAO.save(user);

	}
	
	/**
	 * 获取用户信息
	 */
	@Override
	public User find(Integer id) {
		User user = userDAO.find(id);
		return user;

	}

	/**
	 * 更新用户头像
	 */
	@Override
	public void updateUserPhoto(int id, String url) {
		User user = userDAO.find(id);
		user.setPhoto(url);
		userDAO.save(user);
	}

	/**
	 * 修改密码
	 */
	@Override
	public void updatePassword(User user, String password) {
		user.setPassword(password);
		userDAO.save(user);
	}

	@Override
	public ArrayList<User> list() {
		return (ArrayList<User>) userDAO.query("from User user",new HashMap<String,Object>());
	}
	
	@Override
	public ArrayList<User> listByKeyWord(String keyword) {
		HashMap<String,Object> vars = new HashMap<>();
		vars.put("1","%"+keyword+"%");
		vars.put("2","%"+keyword+"%");
		
		return (ArrayList<User>) userDAO.query("from User user where user.name like ?1 or user.accountName like ?2",vars);
	}

	@Override
	public void delete(Integer id) {
		
		userDAO.delete(userDAO.find(id));
		
	}

	@Override
	public void updateUser(UpdateUserForm form) {
          User user = userDAO.find(form.getId());
          user.setBirthday(form.getBirthday());
          user.setBusiness( form.getBusiness());
          user.setEmail( form.getEmail());
          user.setMobilePhone(form.getMobilePhone());
          user.setPhone(form.getPhone()); 
          user.setSex(form.isSex());
          user.setName(form.getName());
          user.setStatus(form.isStatus());
          if(form.getPosition().getId()!=null)
          user.setPosition(positionDAO.find(form.getPosition().getId()));
          if(form.getDept().getId()!=null)
          user.setDept(deptDAO.find(form.getDept().getId()));
          userDAO.save(user);
	}

	@Override
	public void add(String accountName,String password) throws Exception {
		User user = new User();
		user.setAccountName(accountName);
		user.setPassword(password);
		user.setStatus(true);
		userDAO.add(user);
		
	}

}
